<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif;
    }

    nav {
      background-color: white;
      color: black;
      padding: 10px 0;
      border: 1px solid #555;
      border-radius: 50px;
      display: flex;
      justify-content: center;
      position: relative;
      z-index: 1;
      width: 80%;
      margin: 20px auto;
    }

    ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      display: flex;
    }

    li {
      cursor: pointer;
      position: relative;
      transition: color 0.3s ease;
      padding: 15px 15px;
      border-radius: 4px; /* 添加圆角效果 */
    }

    a {
      text-decoration: none;
      color: black;
      font-size: 16px;
    }

    /* 初始状态下不显示线条 */
    li::after {
      content: '';
      position: absolute;
      bottom: -5px;
      left: 0;
      width: 0;
      height: 4px;
      background-color: #b694c3;
      border-radius: 4px; /* 添加圆角效果 */
      transition: width 0.3s ease, left 0.3s ease;
      clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
      
    }

    /* 选中状态下显示线条 */
    li.active::after {
      width: 100%;
    }

    li.active a {
      color:  #b694c3;
    }

    /* 媒体查询，当页面宽度小于一定值时调整样式 */
    @media (max-width: 768px) {
      nav {
        width: 90%;
        padding: 5px 0;
      }

      li {
        padding: 5px 10px;
      }

      a {
        font-size: 14px;
      }
    }
  </style>
</head>

<body>
  <nav>
    <ul>
      <li class="active"><a href="#">小狗控制</a></li>
      <li><a href="#">高级控制</a></li>
      <li><a href="#">关于电子小狗</a></li>
      <li><a href="#">联系作者</a></li>
    </ul>
  </nav>

  <script>
    const navItems = document.querySelectorAll('nav ul li');

    navItems.forEach(item => {
      item.addEventListener('mouseover', function () {
        const rect = this.getBoundingClientRect();
        const line = this.querySelector('::after');
        const leftPos = rect.left - document.querySelector('nav').getBoundingClientRect().left;
        line.style.left = `${leftPos}px`;
        line.style.width = `${rect.width}px`;
      });

      item.addEventListener('mouseout', function () {
        if (!this.classList.contains('active')) {
          this.querySelector('::after').style.width = '0';
        }
      });

      item.addEventListener('click', function () {
        navItems.forEach(item => item.classList.remove('active'));
        this.classList.add('active');
        const activeLine = document.querySelector('li.active::after');
        activeLine.style.width = `${this.getBoundingClientRect().width}px`;
        activeLine.style.left = `${this.getBoundingClientRect().left - document.querySelector('nav').getBoundingClientRect().left}px`;
      });
    });
  </script>
</body>

</html>